package edu.washington.tcss360.burningpenguins.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Wraps a few JDBC methods for simple use.
 * 
 * @author Chris Gelatt
 * @version 1.0
 * @since 2013-11-2
 *
 */
public class BPSQLiteConnection implements BPDatabaseConnection
{
	private Connection connection;
	private String SQLiteDatabaseFile;
	
	/**
	 * Constructor for operations on the file at the path passed as the parameter.
	 * 
	 * @param SQLiteDatabaseFile The path to the file to use as the DB for this object after instantiation.
	 */
	public BPSQLiteConnection(String SQLiteDatabaseFile)
	{
		try
		{
			Class.forName("org.sqlite.JDBC");
		}
		catch(ClassNotFoundException e)
		{
			//TODO - Improve exception handling
			e.printStackTrace();
		}
		this.SQLiteDatabaseFile = SQLiteDatabaseFile;
	}
	
	public String getSQLiteDatabaseFile()
	{
		return SQLiteDatabaseFile;
	}
	
	public void setSQLiteDatabaseFile(String SQLiteDatabaseFile)
	{
		disconnect();
		this.SQLiteDatabaseFile = SQLiteDatabaseFile;
	}
	
	/**
	 * Connects to the DB the object is associated with.
	 */
	public void connect()
	{
		try
		{
			connection = DriverManager.getConnection("jdbc:sqlite:" + SQLiteDatabaseFile);
		}
		catch(SQLException e)
		{
			//TODO - Improve exception handling
			e.printStackTrace();
		}
	}

	/**
	 * Runs a query to retrieve data from the DB.
	 * 
	 * @param query The query to run.
	 * @return A ResultSet with the results from the query.
	 */
	public ResultSet executeQuery(String query)
	{
		if(connection == null)
		{
			return null;
		}
		
		try
		{
			Statement statement = connection.createStatement();
			return statement.executeQuery(query);
		}
		catch(SQLException e)
		{
			//TODO - Improve exception handling
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * Runs a statement that causes an update to existing data in the DB.
	 * 
	 * @param updateStatement The statement to execute.
	 * @return the number of rows updated.
	 */
	public Integer executeUpdate(String updateStatement)
	{
		if(connection == null)
		{
			return null;
		}
		
		try
		{
			Statement statement = connection.createStatement();
			return statement.executeUpdate(updateStatement);
		}
		catch(SQLException e)
		{
			//TODO - Improve exception handling
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * Disconnects from the database.
	 */
	public void disconnect()
	{
		if(connection != null)
		{
			try
			{
				connection.close();
			}
			catch(SQLException e)
			{
				//TODO - Improve exception handling
				e.printStackTrace();
			}
		}

	}
}
